<?php
namespace app\api\controller;

use app\api\Base;
use think\Config;
use think\Db;
use baseutils\BaseUtil; # 验证类
use com\gdl\newagk\interfaces\AdminUserServiceClient;
use com\gdl\newagk\dataobject\adminuser\UserDTO; 

/**
 * admin后台用户相关接口 包含列表 添加 修改
 * @author tc 2018/04/24
 */

class Adminuser extends Base
{
 	/** 
 	 *  用户列表
     *  用户列表关联查询 存在user表和userCompany表两个之间 不用直接去查询uc
     *  app端注册时，选择平台时同时添加用户到user表  
     *  @param  admin_reg or plaformId
 	 *  @return JSON [description] 400失败 200成功
 	 */
	public function userList() 
    {
    	$msg = ['code'=>400, 'msg'=>'暂无数据', 'data'=>[],'count'=>0];
        $plaformId = $this->request->param('plaformId') ? $this->request->param('plaformId') : 0;
        $liekName = $this->request->param('name') ? $this->request->param('name') : ""; # 姓名 身份证 电话
        $plaformChildId = $this->request->param('plaformChildId') ? $this->request->param('plaformChildId') : "0"; # 所属平台
        $companyId =$this->request->param('companyId') ? $this->request->param('companyId') : ""; # 所属公司
        $departmentId = $this->request->param('deparmentId') ? $this->request->param('deparmentId') : ""; # 所属部门
        $departmentGroupId = $this->request->param('departmentGroupId') ? $this->request->param('departmentGroupId') : ""; # 所属班组
        $groupId = $this->request->param('groupId') ? $this->request->param('groupId') : ""; # 所属分组
        $position = $this->request->param('positionId') ? $this->request->param('positionId') : ""; # 所属职位
        $spce = $this->request->param('spceId') ? $this->request->param('spceId') : ""; # 所属专业
        # 用户状态 1：正常 2：禁用 3：平台禁用 
        $status = $this->request->param('status') ? $this->request->param('status') : ""; # 用户启用状态
        $plaformStatus = $this->request->param('p_status') ? $this->request->param('p_status') : ""; # 废弃参数：用户加入平台审核状态 
        $vface = $this->request->param('v_status') ? $this->request->param('v_status') : ""; # 留底照片审核状态 未审核 5
        $sex = $this->request->param("sex")?$this->request->param("sex"):""; # 1男2女
        $age = $this->request->param('age')?$this->request->param("age"):""; # 年龄区间 0-20

        # 如果basic==all则获取考场用户
        $basicUser = $this->request->param('basic') ?$this->request->param('basic') : "";

        $offset = $this->request->param('offset') ? $this->request->param('offset') : 0; # 分页
        $num = $this->request->param('num') ? $this->request->param('num') : 10; # 条数

        $plaformId = $plaformId?$plaformId:$plaformChildId;
        if($plaformId==0 || empty($plaformId)){
            $adminReg = getApiAdminReg($plaformId,'all');
        }else{
            $adminReg = getApiAdminReg($plaformId,'child');    
        }
        try { 
            \ApiClient::init(Config::get('api.appid'), Config::get('api.secret'), 30, array('gdlApiSdk','gdlCloudSdk'));
            $UserDo = new UserDTO();
            if($liekName){
                $UserDo->data['liekName'] = $liekName;
            }   
            if($companyId){
                $UserDo->data['company_id'] = $companyId;
            }
            if($departmentId){
                $UserDo->data['departmentId'] = $departmentId;
            }
            if($departmentGroupId){
                $UserDo->data['departmentGroupId'] = $departmentGroupId;
            }
            if($groupId){
                $UserDo->data['groupId'] = $groupId;
            }
            if($position){
                $UserDo->data['position'] = $position;
            }
            if($spce){
                $UserDo->data['spce'] = $spce;
            }
            if($status){
                $UserDo->data['status'] = $status;
            }
            if($plaformStatus){
                $UserDo->data['plaformStatus'] = $plaformStatus;
            }
            if($vface){
                $UserDo->data['vface'] = $vface;
            }
            if(!empty($age)){
                $UserDo->data['age'] = $age; 
            }  
            if(isset($sex)&&$sex!=""){
               $UserDo->data['sex']= $sex;  
            } 
            if($basicUser=='all'){
               $UserDo->data['all']= $basicUser;    
            }
            $UserDo->data['admin_reg'] = $adminReg; 
            $UserDo->offset = $offset;
            $UserDo->num = $num;
            $UserDo->id = $plaformId;

            $AdminUserService = new AdminUserServiceClient(NULL);
            \ApiClient::build($AdminUserService);
         
            $result = $AdminUserService->userList($UserDo); 

            if ($result->success == TRUE) {
            	$msg['msg'] = "获取成功";
                $msg['code'] = 200;
                $msg['data'] = $result->data;

                $msg['count'] = is_int(intval($result->message))?intval($result->message):0;

            } else {
                SLogger::getLogger('pub_thrift_service', 'thrift_error')->error('error', $result->message);
            }

        } catch (Exception $ex) {
            SLogger::getLogger('pub_thrift_service', 'thrift_error')->error('thrift call error', $ex);
        }
        return json_encode($msg);
    }
    /**
     * 考场列表
     * @return [type] [description]
     */
    public function basicUserList() 
    {
        $msg = ['code'=>400, 'msg'=>'暂无数据', 'data'=>[],'count'=>0];
        $plaformId = $this->request->param('plaformId') ? $this->request->param('plaformId') : 0;
        $liekName = $this->request->param('name') ? $this->request->param('name') : ""; # 姓名 身份证 电话
        $plaformChildId = $this->request->param('plaformChildId') ? $this->request->param('plaformChildId') : "0"; # 所属平台
        $companyId =$this->request->param('companyId') ? $this->request->param('companyId') : ""; # 所属公司
        $departmentId = $this->request->param('deparmentId') ? $this->request->param('deparmentId') : ""; # 所属部门
        $departmentGroupId = $this->request->param('departmentGroupId') ? $this->request->param('departmentGroupId') : ""; # 所属班组
        $groupId = $this->request->param('groupId') ? $this->request->param('groupId') : ""; # 所属分组
        $position = $this->request->param('positionId') ? $this->request->param('positionId') : ""; # 所属职位
        $spce = $this->request->param('spceId') ? $this->request->param('spceId') : ""; # 所属专业
        # 用户状态 1：正常 2：禁用 3：平台禁用 
        $status = $this->request->param('status') ? $this->request->param('status') : ""; # 用户启用状态
        $plaformStatus = $this->request->param('p_status') ? $this->request->param('p_status') : ""; # 废弃参数：用户加入平台审核状态 
        $vface = $this->request->param('v_status') ? $this->request->param('v_status') : ""; # 留底照片审核状态 未审核 5
        $sex = $this->request->param("sex")?$this->request->param("sex"):""; # 1男2女
        $age = $this->request->param('age')?$this->request->param("age"):""; # 年龄区间 0-20

        # 如果basic==all则获取考场用户
        $basicUser = $this->request->param('basic') ?$this->request->param('basic') : "all";
        # 考场id basic_id
        $basicId = $this->request->param('basicId') ?$this->request->param('basicId') : "";

        $offset = $this->request->param('offset') ? $this->request->param('offset') : 0; # 分页
        $num = $this->request->param('num') ? $this->request->param('num') : 10; # 条数

        $plaformId = $plaformId?$plaformId:$plaformChildId;
        if($plaformId==0 || empty($plaformId)){
            $adminReg = getApiAdminReg($plaformId,'all');
        }else{
            $adminReg = getApiAdminReg($plaformId,'child');    
        }
        try { 
            \ApiClient::init(Config::get('api.appid'), Config::get('api.secret'), 30, array('gdlApiSdk','gdlCloudSdk'));
            $UserDo = new UserDTO();
            if($liekName){
                $UserDo->data['liekName'] = $liekName;
            }   
            if($companyId){
                $UserDo->data['company_id'] = $companyId;
            }
            if($departmentId){
                $UserDo->data['departmentId'] = $departmentId;
            }
            if($departmentGroupId){
                $UserDo->data['departmentGroupId'] = $departmentGroupId;
            }
            if($groupId){
                $UserDo->data['groupId'] = $groupId;
            }
            if($position){
                $UserDo->data['position'] = $position;
            }
            if($spce){
                $UserDo->data['spce'] = $spce;
            }
            if($status){
                $UserDo->data['status'] = $status;
            }
            if($plaformStatus){
                $UserDo->data['plaformStatus'] = $plaformStatus;
            }
            if($vface){
                $UserDo->data['vface'] = $vface;
            }
            if(!empty($age)){
                $UserDo->data['age'] = $age; 
            }  
            if(isset($sex)&&$sex!=""){
               $UserDo->data['sex']= $sex;  
            } 
            if($basicUser=='all'){
               $UserDo->data['basic']= $basicUser;    
            }

            $UserDo->data['admin_reg'] = $adminReg; 
            $UserDo->offset = $offset;
            $UserDo->num = $num;
            $UserDo->id = $plaformId;

            $AdminUserService = new AdminUserServiceClient(NULL);
            \ApiClient::build($AdminUserService);
            $result = $AdminUserService->userList($UserDo);
            $userList = $result->data?$result->data:"";

            if($result->data){
                # 查询考场 
                $basicUserList = Db::name('basic_user')->where(['isdelete'=>0])->field('id,basic_id,identity_id')->select();
                # 0不在考场 1在考场
                
                    for($i=0; $i<count($userList); $i++){
                        $userList[$i]['isBasic'] = 0;
                        if($basicUserList){
                            for($j=0; $j<count($basicUserList); $j++){
                                if($userList[$i]['id']==$basicUserList[$j]['identity_id']&&$basicId==$basicUserList[$j]['basic_id']){
                                    $userList[$i]['isBasic'] = 1;
                                }
                            }
                        }
                    }
            }
            if ($result->success == TRUE) {
                $msg['msg'] = "获取成功";
                $msg['code'] = 200;
                $msg['data'] = $userList;
                $msg['count'] = is_int(intval($result->message))?intval($result->message):0;

            } else {
                SLogger::getLogger('pub_thrift_service', 'thrift_error')->error('error', $result->message);
            }

        } catch (Exception $ex) {
            SLogger::getLogger('pub_thrift_service', 'thrift_error')->error('thrift call error', $ex);
        }
        return json_encode($msg);
    }

    /** 
     *  添加用户
     *  检测用户是否存在 如果存在选择添加到user表和user_company 不存在直接同时添加到uc
     *  @param  $update 添加的数据
     *  @return JSON [description] 400失败 200成功
     */
    public function addUser(){
        $msg = ['code'=>400, 'msg'=>'添加失败', 'data'=>[]];
        # admin 是总平台 那么plaformid = 0  如果江北局是总平台那么久根据plaformid查询出parentid等于0为总平台 
        $data = $this->request->post();
        if(empty($data['idcard'])){
            $msg['msg'] = "请输入身份证";
            return json_encode($msg);
        } 
        if(empty($data['truename'])){
            $msg['msg'] = "请输入姓名";
            return json_encode($msg);
        } 
        if(empty($data['mobile'])){
            $msg['msg'] = "请输入电话";
            return json_encode($msg);
        } 
        if(empty($data['password'])){
            $msg['msg'] = "请填写密码";
            return json_encode($msg);
        }
        $datas = [
            'idcard'=>$data['idcard']?$data['idcard']:"",
            'truename'=>$data['truename']?$data['truename']:"",
            'mobile'=>$data['mobile']?$data['mobile']:"",
            'plaformId'=>$data['plaformId']?$data['plaformId']:0,
            'birthday'=>$data['birthday']?$data['birthday']:"",
            'sex'=>$data['sex']?$data['sex']:"0",
            'age'=>$data['age']?$data['age']:"0",
            'city'=>$data['city']?$data['city']:"0",
            'county'=>$data['county']?$data['county']:"0",
            'password'=>$data['password']?$data['password']:"123456",
            'company_name'=>$data['company_name']?$data['company_name']:"0",
            'position'=>$data['position']?$data['position']:"0",
            'specialty_id'=>$data['specialty_id']?$data['specialty_id']:"0",
            'company_id'=>$data['company_id']?$data['company_id']:"0",
            'departmentid'=>$data['departmentid']?$data['departmentid']:"0",
            'departmentgroupid'=>$data['departmentgroupid']?$data['departmentgroupid']:"0",
            'job_title'=>2,# 1 公司外勤 2 内勤
            'status'=>$data['status']?$data['status'] : 1,
        ];
      
        $datas['username'] = \CUtf8PY::encode($datas['truename'],'all'); # 拼音账号
        $datas['admin_reg'] = getApiAdminReg($datas['plaformId'],'one'); 
        if($datas['plaformId']==0){
            $admin_reg = Db::name('adminUser')->where(['id'=>1])->field('reg')->find();
            $datas['admin_reg'] = $admin_reg['reg']; 
        }  
        try { 
            \ApiClient::init(Config::get('api.appid'), Config::get('api.secret'), 30, array('gdlApiSdk','gdlCloudSdk'));
            $UserDo = new UserDTO();
            $util = new BaseUtil(); 
            if (!$util->isIdCard($datas['idcard'])) {
                $msg['msg'] = "请输入正确的身份证";
                return json_encode($msg);
            }
            if (!$util->IsMobile($datas['mobile'])) {
                $msg['msg'] = "请输入正确的手机号码";
                return json_encode($msg);
            }
            $UserDo->id = $datas['plaformId'];
            $UserDo->data = $datas;

            $AdminUserService = new AdminUserServiceClient(NULL);
            \ApiClient::build($AdminUserService); 
            $result = $AdminUserService->addUser($UserDo); 
            if ($result->success == TRUE) {
                $msg['msg'] = $result->message;
                $msg['code'] = $result->code;
                $msg['data'] = $result->data;

            } else {
                SLogger::getLogger('pub_thrift_service', 'thrift_error')->error('error', $result->message);
            }

        } catch (Exception $ex) {
            SLogger::getLogger('pub_thrift_service', 'thrift_error')->error('thrift call error', $ex);
        }
        return json_encode($msg);
    }

     /** 
     *  修改数据
     *  修改数据到多表 只允许修改密码，姓名，不允许修改身份证
     *  @param  $update 修改的数据
     *  @return JSON [description] 400失败 200成功
     */
    public function updateUser(){
        $msg = ['code'=>400, 'msg'=>'更新成功', 'data'=>[]];
        # admin 是总平台 那么plaformid = 0  如果江北局是总平台那么久根据plaformid查询出parentid等于0为总平台 
        $postData = $this->request->post();
        if(empty($postData['idcard'])){
            $msg['msg'] = "请输入身份证";
            return json_encode($msg);
        } 
        if(empty($postData['truename'])){
            $msg['msg'] = "请输入姓名";
            return json_encode($msg);
        } 
        if(empty($postData['mobile'])){
            $msg['msg'] = "请输入电话";
            return json_encode($msg);
        } 
        if(empty($postData['password'])){
            $msg['msg'] = "请填写密码";
            return json_encode($msg);
        }
        $datas = [
            'id'=>$postData['id'] ?$postData['id']:"",
            'gdl_userid'=>$postData['gdl_userid']?$postData['gdl_userid']:"",
            'userid'=>$postData['userid']?$postData['userid']:"",
            'idcard'=>$postData['idcard']?$postData['idcard']:"",
            'truename'=>$postData['truename']?$postData['truename']:"",
            'mobile'=>$postData['mobile']?$postData['mobile']:"",
            'plaformId'=>$postData['plaformId']?$postData['plaformId']:0, # admin 0 子平台为其他
            'birthday'=>$postData['birthday'],
            'sex'=>$postData['sex'], # 1男 2 女
            'age'=>$postData['age']?$postData['age']:"0",
            'city'=>$postData['city']?$postData['city']:"",
            'county'=>$postData['county']?$postData['county']:"",
            'password'=>$postData['password']?$postData['password']:"", # 修改的时候留空，留空
            'company_name'=>$postData['company_name']?$postData['company_name']:"",
            'position'=>$postData['position']?$postData['position']:"",
            'specialty_id'=>$postData['specialty_id']?$postData['specialty_id']:"",
            'company_id'=>$postData['company_id']?$postData['company_id']:"",
            'departmentid'=>$postData['departmentid']?$postData['departmentid']:"",
            'departmentgroupid'=>$postData['departmentgroupid']?$postData['departmentgroupid']:"",
            'job_title'=>2,# 1 公司外勤 2 内勤
            'status'=>isset($postData['status'])?$postData['status']:0,
        ];
        $datas['admin_reg'] = getApiAdminReg($datas['plaformId'],'one'); 
        
        try { 
            \ApiClient::init(Config::get('api.appid'), Config::get('api.secret'), 30, array('gdlApiSdk','gdlCloudSdk'));
            $UserDo = new UserDTO();
            $util = new BaseUtil(); 
            $idcard = $util->isIdCard($datas['idcard']);
            $phone = $util->IsMobile($datas['mobile']); 
            if (!$idcard) {
                $msg['msg'] = "请输入正确的身份证";
                return json_encode($msg);
            }
            if (!$phone) {
                $msg['msg'] = "请输入正确的手机号码";
                return json_encode($msg);
            }

            $UserDo->id = $datas['plaformId'];
            $UserDo->data = $datas; 
            $AdminUserService = new AdminUserServiceClient(NULL);
            \ApiClient::build($AdminUserService);
            
            $result = $AdminUserService->updateUser($UserDo);  

            if ($result->success == TRUE) {
                $msg['msg'] = $result->message;
                $msg['code'] = $result->code;
                $msg['data'] = $result->data;

            } else {
                SLogger::getLogger('pub_thrift_service', 'thrift_error')->error('error', $result->message);
            }

        } catch (Exception $ex) {
            SLogger::getLogger('pub_thrift_service', 'thrift_error')->error('thrift call error', $ex);
        }
        return json_encode($msg);
    }
    
    /** 
     *  检查用户是否存在
     *  检查用户是否存在 存在返回数据 不存在不返回
     *  @param  $update 修改的数据
     *  @return JSON [description] 400失败 200成功
     */
    public function selectEmptyUser(){
        $msg = ['code'=>400, 'msg'=>'暂无数据', 'data'=>[]];
        $plaformId = $this->request->param('plaformId') ? $this->request->param('plaformId') : 0;
        $idcard = $this->request->param('idcard') ? $this->request->param('idcard') : "";
        try { 
            \ApiClient::init(Config::get('api.appid'), Config::get('api.secret'), 30, array('gdlApiSdk','gdlCloudSdk'));
            $UserDo = new UserDTO();
            $util = new BaseUtil(); 
            if (!$util->isIdCard($idcard)) {
                $msg['msg'] = "请输入正确的身份证号";
                return json_encode($msg);
            } 

            $UserDo->id = $plaformId;
            $UserDo->field = $idcard;

            $AdminUserService = new AdminUserServiceClient(NULL);
            \ApiClient::build($AdminUserService);

            $result = $AdminUserService->selectEmptyUser($UserDo); 

            if ($result->success == TRUE) {
                $msg['msg'] = $result->message;
                $msg['code'] = $result->code;
                $msg['data'] = $result->data;
                if($result->code==200){
                    $msg['data'] = $result->data[0];
                }

            } else {
                SLogger::getLogger('pub_thrift_service', 'thrift_error')->error('error', $result->message);
            }

        } catch (Exception $ex) {
            SLogger::getLogger('pub_thrift_service', 'thrift_error')->error('thrift call error', $ex);
        }
        return json_encode($msg);
    } 
    /**
     * 用户详情
     * plaform id=0 总平台 id!=0 子平台
     */
    public function userInfo(){
        $msg = ['code'=>400, 'msg'=>"获取用户信息失败", "data"=>[]];
        $palformId = $this->request->param("plaform_id") ? $this->request->param("plaform_id") : 0;
        $adminReg = $this->request->param("admin_reg") ? $this->request->param("admin_reg") : "";
        $userid = $this->request->param("userid") ? $this->request->param("userid") : "";
        $gdl_userid = $this->request->param("gdl_userid") ? $this->request->param("gdl_userid") : "";
        $id = $this->request->param("companyUserId") ? $this->request->param("companyUserId") : "";

        if ( empty($userid) || empty($gdl_userid) ) {
            $msg['msg'] = "缺少必要参数";
            return json_encode($msg);
        }

        try{

            \ApiClient::init(Config::get('api.appid'), Config::get('api.secret'), 30, array('gdlApiSdk','gdlCloudSdk'));
            $UserDo = new UserDTO(); 
            $UserDo->id = $palformId;
            $UserDo->data = ['gdl_userid'=>$gdl_userid, 'userid'=>$userid,'id'=>$id];
            $AdminUserService = new AdminUserServiceClient(NULL);
            \ApiClient::build($AdminUserService);  
            $result = $AdminUserService->userInfo($UserDo); 
            if($result->success == true){
                $msg['msg'] = $result->message;
                $msg['code'] = $result->code;
                if($result->code==200){
                    $msg['data'] = $result->data[0];
                }
            }
 
        }catch(Exception $e){
            $msg['msg'] = $e->getMessage();
        }

        return json_encode($msg);
    }

     /**
     * 修改用户留的照片
     * plaform id=0 总平台 id!=0 子平台
     */
    public function editFace(){
        $msg = ['code'=>400, 'msg'=>"修改失败", "data"=>[]];
        $palformId = $this->request->param("plaform_id") ? $this->request->param("plaform_id") : "";
        $adminReg = $this->request->param("admin_reg") ? $this->request->param("admin_reg") : "";  
        $id = $this->request->param("companyUserId") ? $this->request->param("companyUserId") : "";
        $status = $this->request->param("vface") ? $this->request->param("vface") : 1;
        $text = $this->request->param("facetext") ? $this->request->param("facetext") : "";

        if ( empty($id) ) {
            $msg['msg'] = "请选择需要修改的用户";
            return json_encode($msg);
        }

        try{

            \ApiClient::init(Config::get('api.appid'), Config::get('api.secret'), 30, array('gdlApiSdk','gdlCloudSdk'));
            $UserDo = new UserDTO(); 
            $UserDo->id = $palformId;
            $UserDo->data = ['text'=>$text, 'statsu'=>$status,'id'=>$id];
            $AdminUserService = new AdminUserServiceClient(NULL);
            \ApiClient::build($AdminUserService);  
            $result = $AdminUserService->editFace($UserDo); 
            if($result->success == true){
                $msg['msg'] = $result->message;
                $msg['code'] = $result->code;
            }
 
        }catch(Exception $e){
            $msg['msg'] = $e->getMessage();
        }

        return json_encode($msg);
    }
    /**
     * 获取用户留底照片信息
     */
    public function faceInfo(){
        $id = $this->request->param("identityId") ? $this->request->param("identityId") : "";
        $admin_reg = $this->request->param("admin_reg") ? $this->request->param("admin_reg") :"";
        try{
            $db = Db::name("userCompany");
            $where['id'] = $id;
            $lists = $db
                ->alias('a')
                ->join("user u", "a.userId = u.userId", 'left') 
                ->field('u.username,u.realName,u.idcard,a.photoCollect,a.vface,a.faceText')
                ->where($where)->select(); 
            if($lists){
                $msg['msg'] = "获取成功";
                $msg['data'] = $lists;
                $msg['code'] = 200;
            }
        }catch(Exception $e){
            $msg['msg'] = $e->getMessage();
        }
        return json_encode($msg);
    }
    /**
     * 修改用户状态
     * status 0：禁用 1:启用  2：平台禁用
     * # 两个只传一个 多选中全部删除
     * post 
     */
    public function editStatus(){
        $msg = ['code'=>400, 'msg'=>"请勿重复操作", 'data'=>[]];
        $plaformId = $this->request->param('plaformId') ? $this->request->param('plaformId') : 0;
        $admin_reg = $this->request->param('reg') ? $this->request->param('reg') : "";
        $id = $this->request->param('id') ? $this->request->param('id') : "";
        $userid = $this->request->param('userid')?$this->request->param('userid'):"";
        $postData = $this->request->post();
        $status = $postData['status']?$postData['status']:0;
        try{ 
            $where['id'] = ["in", $id];
            $userWhere['userId'] = ['in',$userid];

            if($plaformId==0){
                # 启用
                if($status==1){
                    # user启用全部启用
                    if(!empty($userid)){
                        $userRet = Db::name('user')->where($userWhere)->setField(['status'=>1]);
                        if($userRet){
                            $companyWhere['userId'] = ['in',$userId];
                            Db::name('userCompany')->where($companyWhere)->setField(['status'=>1]);
                        }
                    }
                    # 只传id 修改user_company状态
                    if(!empty($id)){
                        $companyRet = Db::name('userCompany')->where($where)->setField(['status'=>1]);   
                    }
                    
                }else{
                    # user禁用全部禁用
                    if(!empty($userid)){
                        $userRet = Db::name('user')->where($userWhere)->setField(['status'=>2]);
                        if($userRet){
                            $companyWhere['userId'] = ['in',$userId];
                            Db::name('userCompany')->where($companyWhere)->setField(['status'=>2]);
                        }
                    }
                    # 只传id 修改user_company状态
                    if(!empty($id)){
                        $companyRet = Db::name('userCompany')->where($where)->setField(['status'=>2]);   
                    }
                }


            }else{ 
                $companyRet = Db::name('userCompany')->where($where)->setField(['status'=>$status]);

            }
            if($companyRet || $userRet){
                # 如果用户被禁用则禁止该用户登录 
                $msg['code'] = 200;
                if($status==1){
                    $msg['msg'] = "启用成功";
                }else{
                    $msg['msg'] = "禁用成功";
                }
                
               // return json_encode($msg);

                try{
                    \ApiClient::init(Config::get('api.appid'), Config::get('api.secret'), 30, array('gdlApiSdk','gdlCloudSdk'));
                    $UserDo = new UserDTO();
                    $UserDo->id = $plaformId;
                    $UserDo->data = ['info'=>'disable','id'=>$id];
                    $AdminUserService = new AdminUserServiceClient(NULL);
                    \ApiClient::build($AdminUserService);
             
                    # 如果禁用的company用户则通知app端账号异常
                    if($id){
                        if($status==0 || empty($status)){
                            $result = $AdminUserService->editStatus($UserDo); 
                            // var_dump($result);exit;
                            if($result->code==200){
                                $msg['msg'] = "禁用成功";
                            }else{
                                $msg['msg'] = "禁用成功但通知APP失败";
                            }
                        }
                    } 
                }catch(Exception $e){
                    $msg['msg'] = "禁用成功但通知APP失败";
                    $msg['code'] = 200;
                    return json_encode($msg);    
                }

            }

        }catch(Exception $e){
            $msg['msg'] = $e->getMessage();
        }
        return json_encode($msg);
    }

     /**
     * 是否删除用户
     * 1:删除  传入id 删除公司用户 传userid删主要用户
     */
    public function deleteUser(){

        $msg = ['code'=>400, 'msg'=>"请勿重复操作", 'data'=>[]];
        $plaformId = $this->request->param('parform_id') ? $this->request->param('parform_id') : 0;
        $admin_reg = $this->request->param('reg') ? $this->request->param('reg') : "";
        $id = $this->request->param('id') ? $this->request->param('id') : ""; # 1,2,3
        $userid = $this->request->param('userid')?$this->request->param('userid'):"";#123逗号分隔
        $status = $this->request->param('delete') ? $this->request->param('delete') : ""; # 0 还原 1删除 d
        # 如果两个都传了只三user_company里的数据
        if($id&&$userid){
            $userid = "";
        }

       if(empty($id)&&empty($userid)){
            $msg['msg'] = "请选择需要删除的用户";
            return json_encode($msg);
       }

        try{
            if(!empty($id)){
                $where['id'] = ["in", $id];
                $companyDel = Db::name('userCompany')->where($where)->setField(['isdelete'=>1]);    
            }
            if(!empty($userid)){
                $userWhere['userId'] = ["in", $userid];
                $userDel = Db::name('user')->where($userWhere)->setField(['isdelete'=>1]);           
            }
            
            if($companyDel || $userDel){
                $msg['code'] = 200;
                $msg['msg'] = "删除成功";

                try{
                    \ApiClient::init(Config::get('api.appid'), Config::get('api.secret'), 30, array('gdlApiSdk','gdlCloudSdk'));
                    $UserDo = new UserDTO();
                    $UserDo->id = $plaformId;
                    $UserDo->data = ['info'=>'delete','id'=>$id];
                    $AdminUserService = new AdminUserServiceClient(NULL);
                    \ApiClient::build($AdminUserService);
             
                    # 如果禁用的company用户则通知app端账号异常
                    if(!empty($id)){
                        if($status==1){
                            $result = $AdminUserService->editStatus($UserDo); 
                            if($result->code==200){
                                $msg['msg'] = "删除成功";
                            }else{
                                $msg['msg'] = "删除成功但通知APP失败";
                            }
                        }
                    } 
                }catch(Exception $e){
                    $msg['msg'] = "删除成功但通知APP失败";
                    $msg['code'] = 200;
                    return json_encode($msg);    
                }


            }
        }catch(Exception $e){
            $msg['msg'] = $e->getMessage();
        }
        return json_encode($msg);
    }
    /**
     * 获取平台列表
     */
    public function getPlaformList(){
        $msg = ['code'=>400,'msg'=>'暂无数据', 'data'=>[]];
        $plaformId = $this->request->param("plaformId") ? $this->request->param("plaformId"):0;
        $admin_reg = $this->request->param("admin_reg") ? $this->request->param("admin_reg"):"";

        try{
            $db = Db::name("plaform");
            $where['isdelete'] = 0;
            $where['status'] = 1;
            if($plaformId!=0 && !empty($plaformId)){
                $map = array('id'=>$plaformId,'parentid'=>$plaformId);
                // $where['id'] = $plaformId;
                // $where['parentid'] = $plaformId;
            } 
            $filed = "id,reals,adminRealname,name,admin_reg";
            if($map){
                $list = $db->where($where)->where(function ($q) use($map) {$q->whereOr($map);});
                $list = $db->field($field)->select(); 
            }else{
                $list = $db->where($where)->field($filed)->select();    
            }
            
            if($list){
                $msg['code'] = 200;
                $msg['msg'] = "获取成功";
                $msg['data'] = $list;
            }
        }catch(Exception $e){
            $msg['msg'] = $e->getMessage();
        }
        return json_encode($msg);
    }
    /**
     * 获取公司列表
     */
    public function getCompanyList(){
        $msg = ['code'=>400,'msg'=>'暂无数据', 'data'=>[]];
        $plaformId = $this->request->param("plaformId") ? $this->request->param("plaformId"):0;
        $admin_reg = $this->request->param("admin_reg") ? $this->request->param("admin_reg"):"";
        if($plaformId==0 || empty($plaformId)){
            $adminReg = getApiAdminReg($plaformId,'all');
        }else{
            $adminReg = getApiAdminReg($plaformId,'child');
        }
        $regArray = explode("','",$adminReg); 
        try{
            $where['admin_reg'] = ['in',$regArray];
            $where['isdelete'] = 0;
            $where['status'] = 1;
            $list = Db::name('company')->where($where)->field("id,name,admin_reg")->select();
            if($list){
                $msg['code'] = 200;
                $msg['msg'] = "获取成功";
                $msg['data'] = $list;
            }
        }catch(Exception $e){
            $msg['msg'] = $e->getMessage();
        }
        
        return json_encode($msg);
    }
    /**
     * 根据公司获取部门列表
     */
    public function getDepartmentList(){
        $msg = ['code'=>400,'msg'=>'暂无数据', 'data'=>[]];
        $companyId = $this->request->param("companyId") ? $this->request->param("companyId"):"";
        $admin_reg = $this->request->param("admin_reg") ? $this->request->param("admin_reg"):"";
        $type = $this->request->param('type')?$this->request->param("type"):"";
        if(empty($companyId)){
            $msg['msg'] = "请选择相应公司";
            return json_encode($msg);
        }

        try{
            $where['companyId'] = $companyId;
            $where['isdelete'] = 0;
            $where['status'] = 1;
            $where['pid'] = 0;
            $db = Db::name('department');
            $list = $db->where($where)->field('id,name,admin_reg')->select();
            if($list){
                $msg['code'] = 200;
                $msg['msg'] = "获取成功";
                $msg['data'] = $list;
            }
        }catch(Exception $e){
            $msg['msg'] = $e->getMessage();
        }
        return json_encode($msg);
    }
    /**
     * 根据部门id获取班组
     */
    public function getGroupList(){
        $msg = ['code'=>400,'msg'=>'暂无数据', 'data'=>[]];
        $departmentId = $this->request->param("departmentId") ? $this->request->param("departmentId"):"";
        $admin_reg = $this->request->param("admin_reg") ? $this->request->param("admin_reg"):"";
        if(empty($departmentId)){
            $msg['msg'] = "请选择相应部门";
            return json_encode($msg);
        }
        try{
            $db = Db::name('department');
            $where['pid'] = $departmentId;
            $where['isdelete'] = 0;
            $where['status'] = 1;
            $list = $db->where($where)->field("id,name")->select();
            if($list){
                $msg["code"] = 200;
                $msg["msg"] = "获取成功";
                $msg['data'] = $list;
            }
        }catch(Exception $e){
            $msg['msg'] = $e->getMessage();
        }
        return json_encode($msg);
    }
    /**
     * 根据公司id获取职位和专业
     */
    public function getPositionAndMajor(){
        $msg = ['code'=>400,'msg'=>'暂无数据', 'data'=>[]];
        $companyId = $this->request->param("companyId") ? $this->request->param("companyId"):0;
        $type = $this->request->param("type") ? $this->request->param("type"):"0"; # 0专业 1职位
        $admin_reg = $this->request->param("admin_reg") ? $this->request->param("admin_reg"):"";
        try{
            $where['companyId'] = $companyId;
            $where['isdelete'] = 0;
            $where['status'] = 1;
            $where['type'] = $type;
            $list = Db::name('userSpecialty')->where($where)->field('id,name')->select();
            if($list){
                $msg['code'] = 200;
                $msg['msg'] = "获取成功";
                $msg['data'] = $list;
            }
        }catch(Exception $e){
            $msg['msg'] = $e->getMessage();
        }
        return json_encode($msg);   
    }

    /**
     * 导出用户详情
     */
    public function downUserExecl(){
        ob_end_clean(); # 清空缓冲区
        $msg = ['code'=>400, 'msg'=>'暂无数据', 'data'=>[],'count'=>0];
        $plaformId = $this->request->param('plaformId') ? $this->request->param('plaformId') : 0;
        $liekName = $this->request->param('name') ? $this->request->param('name') : ""; # 姓名 身份证 电话
        $plaformChildId = $this->request->param('plaformChildId') ? $this->request->param('plaformChildId') : "0"; # 所属平台
        $companyId =$this->request->param('companyId') ? $this->request->param('companyId') : ""; # 所属公司
        $departmentId = $this->request->param('deparmentId') ? $this->request->param('deparmentId') : ""; # 所属部门
        $departmentGroupId = $this->request->param('departmentGroupId') ? $this->request->param('departmentGroupId') : ""; # 所属班组
        $groupId = $this->request->param('groupId') ? $this->request->param('groupId') : ""; # 所属分组
        $position = $this->request->param('positionId') ? $this->request->param('positionId') : ""; # 所属职位
        $spce = $this->request->param('spceId') ? $this->request->param('spceId') : ""; # 所属专业
        # 用户状态 1：正常 2：禁用 3：平台禁用 
        $status = $this->request->param('status') ? $this->request->param('status') : ""; # 用户启用状态
        $plaformStatus = $this->request->param('p_status') ? $this->request->param('p_status') : ""; # 废弃参数：用户加入平台审核状态 
        $vface = $this->request->param('v_status') ? $this->request->param('v_status') : ""; # 留底照片审核状态 未审核 5
        $sex = $this->request->param("sex")?$this->request->param("sex"):""; # 1男2女
        $age = $this->request->param('age')?$this->request->param("age"):""; # 年龄区间 0-20

        $offset = $this->request->param('offset') ? $this->request->param('offset') : 0; # 分页
        $num = $this->request->param('num') ? $this->request->param('num') : 10; # 条数

        $selectId = $this->request->param('selectId') ? $this->request->param('selectId') : ""; # 指定数据导出

        $plaformId = $plaformId?$plaformId:$plaformChildId;
        if($plaformId==0 || empty($plaformId)){
            $adminReg = getApiAdminReg($plaformId,'all');
        }else{
            $adminReg = getApiAdminReg($plaformId,'child');    
        }
        // var_dump($this->request->get());exit;
        try { 
            \ApiClient::init(Config::get('api.appid'), Config::get('api.secret'), 30, array('gdlApiSdk','gdlCloudSdk'));
            $UserDo = new UserDTO();
            if($liekName){
                $UserDo->data['liekName'] = $liekName;
            }   
            if($companyId){
                $UserDo->data['company_id'] = $companyId;
            }
            if($departmentId){
                $UserDo->data['departmentId'] = $departmentId;
            }
            if($departmentGroupId){
                $UserDo->data['departmentGroupId'] = $departmentGroupId;
            }
            if($groupId){
                $UserDo->data['groupId'] = $groupId;
            }
            if($position){
                $UserDo->data['position'] = $position;
            }
            if($spce){
                $UserDo->data['spce'] = $spce;
            }
            if($status){
                $UserDo->data['status'] = $status;
            }
            if($plaformStatus){
                $UserDo->data['plaformStatus'] = $plaformStatus;
            }
            if($vface){
                $UserDo->data['vface'] = $vface;
            }
            if(!empty($age)){
                $UserDo->data['age'] = $age; 
            }  
            if(isset($sex)&&$sex!=""){
               $UserDo->data['sex']= $sex;  
            }
            if($selectId){
                 $UserDo->data['selectId']= $selectId;     
            } 
            $UserDo->data['admin_reg'] = $adminReg; 
            $UserDo->offset = $offset;
            $UserDo->num = $num;
            $UserDo->id = $plaformId;

            $AdminUserService = new AdminUserServiceClient(NULL);
            \ApiClient::build($AdminUserService);
         
            $result = $AdminUserService->userList($UserDo);
            if ($result->success == TRUE) {
                $header = ['USERID/ID','姓名','身份证','手机号','性别','年龄','所属平台','公司','部门','职位','班组','专业','留底','账号状态'];
                $list = [];
                foreach($result->data as $key=>$v){ 
                    $list[]= [
                        $v['id']."/".$v['userId'],
                        $v['realName'],
                        "|--".$v['idcard'],
                        "|--".$v['mobile'],
                        $this->getSex($v['sex']),
                        $v['age'],
                        $v['re_plaform'],
                        $v['re_company'],
                        $v['re_depart'],
                        $v['re_position'],
                        $v['re_departGroup'],
                        $v['re_spce'],
                        $this->getVface($v['vface']), 
                        $this->getStatsu($v['status']),
                    ];
                } 
                $version = '2007';
                //\Excel::export($header, $list, "用户列表", $version);
				$distance = ['C'=>['t'=>'text'],'D'=>['t'=>'text']];
				\Excel::exportDistance($header, $list, "用户列表", $version,$distance);
            } else {
                $msg['msg'] = "没有可导出的数据";
            }

        } catch (Exception $ex) {
            $msg['msg'] = "没有可导出的数据";
        }
        return json_encode($msg);
    }
    # 男女
    public function getSex($sex=0){
        $sexs = "男";
        if($sex==0){
            $sexs = "男";
        }
        if($sex==1){
            $sexs = "女";
        }

        return $sexs;
    }
    # 状态
    public function getVface($face=0){
        $faces = "未上传";
        if($face==0){
            $faces = "未上传";
        }
        if($face==1){
            $faces = "审核失败";   
        }
        if($face==2){
            $faces = "审核通过";
        }
        if($face==3){
            $faces = "审核中";
        }
        return $faces;
    }
    #账号状态
    public function getStatsu($status=0){
        $status_str = "未知";
        if($status==0){
            $status_str = "禁用";
        }
        if($status==1){
            $status_str = "正常";
        }
        if($status==2){
            $status_str = "平台已禁用";
        }
        return $status_str;
    }
    
}
